#!/bin/bash 


## $1 working path 
Target_Path=$1
Prefix=$2
CMD_cut=`which cut`
CMD_rm=`which rm`

do_change()
{
    local path=$1
    local level=$2
    local Name=$3
    local Name_count=""
    local tab_string=""

    local Folder_List=`ls -l $path | egrep '^d' | awk '{print $9}'`
    local File_List=`ls -l $path | egrep '^-' | awk '{print $9}'`
    local File_count=`ls -l $path | egrep '^-' | awk '{print $9}' | wc -w`


    abc=`echo $File_List | grep "Thumbs.db"` 
    if ((!$?)) 
    then 
        File_count=$(($File_count-1))
    fi 

    for ((i=0;i<=$level;i++))
    do
        tab_string=$tab_string"."
    done

    level=$(($level+1))
    for sub_dir in $Folder_List
    do
        if [ $level -gt 1 ]
        then
            Inject_name=$Name"_"$sub_dir
        else 
            Inject_name=$sub_dir
        fi
        do_change "$path/$sub_dir" $level $Inject_name
    done

    echo -e $tab_string "d $path"
  
    cd $path 
    mkdir temp
    for sub_file in $File_List
    do 

        Ext_name=`echo $sub_file | awk -F . '{print $NF}' `
        if [ $Ext_name = "JPG" ] || [ $Ext_name = "jpg" ] || [ $Ext_name = "jpeg" ]
        then
            Name_count=$(($Name_count+1))
            Name_String=`printf "%04d\n" $Name_count`
            mv $sub_file "temp/"$Name"_"$Name_String".jpg"
        else 
            echo $Sub_name > /tmp/111
        fi 
        
        
    done
    mv temp/*.jpg . 
    rm -rf temp 
}

echo "Start Path = $Target_Path"

do_change $Target_Path 0 $Prefix
